<template>
    <div class="image-list-box">
        <div class="image-list-part">
            <el-table
                v-loading="initDataLoading"
                class="table-class"
                :data="images"
                style="width: 100%"
            >
                <el-table-column
                    prop="id"
                    label="ID"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="original"
                    label="来源"
                    width="100">
                    <template slot-scope="scope">
                        <div v-show="scope.row.original==='cover'">
                            <el-tag type="info">封面</el-tag>
                        </div>
                        <div v-show="scope.row.original==='avatar'">
                            <el-tag type="primary">头像</el-tag>
                        </div>
                        <div v-show="scope.row.original==='article'">
                            <el-tag type="danger">文章</el-tag>
                        </div>
                        <div v-show="scope.row.original==='loop'">
                            <el-tag type="warning">轮播图</el-tag>
                        </div>
                        <div v-show="scope.row.original==='friend_link'">
                            <el-tag type="success">友情链接</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="图片名称"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="cover"
                    label="封面"
                    width="120">
                    <template slot-scope="scope">
                        <img :src="'/portal/image/' + scope.row.url" width="120px" alt="picture">
                    </template>
                </el-table-column>
                <el-table-column
                    prop="state"
                    label="状态"
                    width="100">
                    <template slot-scope="scope">
                        <div v-show="scope.row.state==='2'">
                            <el-tag type="info">草稿</el-tag>
                        </div>
                        <div v-show="scope.row.state==='1'">
                            <el-tag type="primary">正常</el-tag>
                        </div>
                        <div v-show="scope.row.state==='0'">
                            <el-tag type="danger">禁用</el-tag>
                        </div>
                        <div v-show="scope.row.state==='3'">
                            <el-tag type="success">置顶</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="url"
                    label="url"
                    width="120">
                </el-table-column>
                <el-table-column
                    label="创建时间"
                    width="120">
                    <template slot-scope="scope">
                        <span v-text="formatDate(scope.row.createTime)"></span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="更新时间"
                    width="120">
                    <template slot-scope="scope">
                        <span v-text="formatDate(scope.row.updateTime)"></span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="100">
                    <template slot-scope="scope">
                        <el-button type="danger"
                                   size="mini"
                                   @click="deleteItem(scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="image-page-navigation" style="margin-top: 10px">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNavigation.currentPage"
                :page-sizes="[5]"
                :page-size="pageNavigation.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageNavigation.totalElements">
            </el-pagination>
        </div>

        <div class="image-dialog-part">
            <!--            删除分类的弹窗-->
            <el-dialog
                :close-on-press-escape="false"
                :close-on-click-modal="false"
                title="提示"
                :visible.sync="deleteDialogVisible"
                width="400px">
                <span>你确定要删除:{{ deleteMessage }} 这张图片吗?</span>
                <span slot="footer" class="dialog-footer">
                <el-button @click="deleteDialogVisible = false">取 消</el-button>
                <el-button type="danger" @click="doDeleteItem()">删除</el-button>
              </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {success_code} from "@/utils/ResponseState";
import {formatDate} from "@/utils/date";
import {listCategories} from "@/api/categoryAdminApi";
import {postFriendLink, updateFriendLink} from "@/api/friend-link-admin-api";
import {deleteImage, listImages} from "@/api/image-admin-api";

export default {
    name: "manage-image",
    data() {
        return {
            categories: [],
            searchForm: {
                keyword: '',
                state: '',
                categoryId: ''
            },
            formName: "searchFormName",
            images: [],
            deleteDialogVisible: false,
            deleteMessage: "",
            deleteItemId: "",
            editTitle: "添加",
            editorBtnText: "",
            editorDialogVisible: false,
            image: {
                id: '',
                url: '',
                contentType: '',
                state: '1',
                name: '',
                avatar: '',
                path: '',
                userId: '',
                createTime: '',
                updateTime: '',
                original: ''
            },
            initDataLoading: false,
            pageNavigation: {
                currentPage: 1,
                totalPages: 1,
                pageSize: 5,
                totalElements: 10
            },
        }
    },
    methods: {
        showAddFriendLink() {
            this.editTitle = '添加友情链接';
            this.editorBtnText = '添 加';
            this.editorDialogVisible = true;
        },
        deleteItem(item) {
            this.deleteDialogVisible = true;
            this.deleteMessage = item.name;
            this.deleteItemId = item.id;
            // console.log(item);
        },
        doDeleteItem() {
            deleteImage(this.deleteItemId).then(result => {
                if (result.code === success_code) {
                    this.$message.success(result.message);

                    this.initData();
                } else {
                    this.$message.error(result.message);
                }
            })

            this.deleteDialogVisible = false;
        },
        formatDate(dataStr) {
            let date = new Date(dataStr);
            return formatDate(date, "yyyy-MM-dd hh:mm:ss");
        },
        initData() {
            this.initDataLoading = true;
            listImages(this.pageNavigation.currentPage,
                this.pageNavigation.pageSize,
                'all').then(result => {
                if (result.code === success_code) {
                    this.images = result.data.content;

                    this.pageNavigation.totalElements = result.data.totalElements;
                    this.pageNavigation.totalPages = result.data.totalPages;
                    this.pageNavigation.currentPage = result.data.currentPage;
                } else {
                    this.$message.error(result.message);
                }
            })

            this.initDataLoading = false;

            listCategories().then(result => {
                if (result.code === success_code) {
                    this.categories = result.data;
                    this.categories.push({
                        id: '',
                        name: '所有分类'
                    })
                } else {
                    this.$message.error("获取文章分类失败");
                }
            });
        },
        showAddCategory() {
            this.editTitle = '添加友情链接';
            this.editorBtnText = '添 加';
            this.editorDialogVisible = true;
        },
        postAndPutLooper() {
            // check data
            if (this.image.avatar === "") {
                this.$message.warning("图片不能为空")
                return;
            }

            if (this.image.contentType === "") {
                this.$message.warning("标题不能为空");
                return;
            }
            if (this.image.name === "") {
                this.$message.warning("链接不能为空");
                return;
            }

            if (!this.image.name.startsWith("http://") && !this.image.name.startsWith("https://")) {
                this.$message.warning("目标链接格式不正确");
                return;
            }


            if (this.image.id === '') {
                postFriendLink(this.image).then(result => {
                    if (result.code === success_code) {
                        this.$message({
                            type: 'success',
                            center: true,
                            message: result.message
                        })

                        this.initData()
                    } else {
                        this.$message.error(result.message);
                    }
                });
            } else {
                // console.log(this.friendLink.logo);
                updateFriendLink(this.image).then(result => {
                    if (result.code === success_code) {
                        // change ui state
                        this.$message.success(result.message)

                        this.initData()
                    } else {
                        // change ui state
                        this.$message.error(result.message);
                    }
                });
            }

            this.resetData();
            this.editorDialogVisible = false
        },
        resetData() {
            this.image.id = '';
            this.image.contentType = '';
            this.image.order = 1;
            this.image.state = '1';
            this.image.name = '';
            this.image.avatar = '';
        },
        // 图片上传后
        handleAvatarSuccess(response) {
            if (response.code === success_code) {
                this.$message.success(response.message);

                this.image.avatar = '/portal/image/' + response.data.path;
            } else {
                this.$message.error(response.message);
            }
        },
        // 图片上传前
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 5;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        clearSearchForm() {
            this.$refs[this.formName].resetFields();
        },
        // 搜索页面大小改变的监听
        handleSizeChange(val) {
            this.pageNavigation.pageSize = val;
        },
        // 搜索页码改变的监听
        handleCurrentChange(val) {
            this.pageNavigation.currentPage = val;

            this.initData();
        },
    },
    mounted() {
        // init data
        this.initData();
    }
}
</script>

<style scoped>

</style>